package com.iot.service.impl;

import com.iot.dao.FastDfsDao;
import com.iot.dao.RedisDao;
import com.iot.domain.Album;
import com.iot.domain.MvFile;
import com.iot.service.FastDfsService;
import com.iot.service.RedisService;
import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
public class FastDfsServiceImpl implements FastDfsService  {


    @Autowired
    private FastDfsDao fastDfsDao;


    @Autowired
    private RedisService redisService;

    /*封装 file的对象*/
    @Override
    public List<MvFile> getMvFile(List<MultipartFile> files) throws IOException {
        //对files  进行遍历 封装实体类对象

        List<MvFile> fileList = new ArrayList<>();

        for (MultipartFile file :
                files) {


            String originalFilename = file.getOriginalFilename();
            MvFile mvFile = new MvFile();

            //切割获取文件的后缀名
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            //设置新的文件名

            String newFileName = UUID.randomUUID() +"."+ fileType;

            //创建web服务器的保存文件的目录
            File newFile = new File("/Volumes/c/upload", newFileName);


            //将路径转化为文件
            file.transferTo(newFile);

            //获取文件的绝对的路径
            String absolutePath = newFile.getAbsolutePath();

            //封装文件实体
            mvFile.setPath(absolutePath);
            //设置源文件的名字
            mvFile.setOldFileName(originalFilename);
            mvFile.setFileType(fileType);
            Date date = new Date();
            mvFile.setCreateTime(date);
            mvFile.setUpdateTime(date);
            //设置新的文件名
            mvFile.setNewFileName(newFileName);
            fileList.add(mvFile);

        }

        return fileList;


    }


    //创建相册
    @Override
    public void uploadFile(Album album , List<MultipartFile> files) throws IOException, MyException {


        //先封装数据为 MvFile  对象
        List<MvFile> mvFiles = getMvFile(files);

        List<MvFile> fileList = fastDfsDao.uploadFile(mvFiles);

        //同时将信息保存到 redis
        redisService.saveFile(album,fileList);

    }

    /*根据相册的名称上传照片*/
    @Override
    public void uploadFileByName(String name, List<MultipartFile> files) throws IOException, MyException {


        //封装MvFile对象
        List<MvFile> mvFile = getMvFile(files);

        //上传到服务器
        List<MvFile> fileList = fastDfsDao.uploadFile(mvFile);

        //保存到redis
        redisService.uploadPictureByName(name,fileList);
    }


}
